package cn.hd01.thymeleaf;

import java.util.ArrayList;
import java.util.List;

import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;
import org.thymeleaf.dom.Node;
import org.thymeleaf.dom.Text;
import org.thymeleaf.processor.element.AbstractMarkupSubstitutionElementProcessor;
import org.thymeleaf.spring4.context.SpringWebContext;

import cn.hd01.repository.entity.Permissions;
import cn.hd01.service.PermissionsService;
import cn.hd01.util.TreeNode;

public class PermissionsProcessor extends AbstractMarkupSubstitutionElementProcessor {

	public PermissionsProcessor() {
		super("permissions");
	}

	@Override
	public int getPrecedence() {
		return 0;
	}

	@Override
	protected List<Node> getMarkupSubstitutes(Arguments arguments, Element element) {
		SpringWebContext context = (SpringWebContext) arguments.getContext();
		PermissionsService service = context.getApplicationContext().getBean(PermissionsService.class);
		TreeNode<Permissions> permissionsTree = service.getPermissionsTree();

		Element ul = new Element("ul");
		for (TreeNode<Permissions> node : permissionsTree.getChildren()) {
			ul.addChild(build(node));
		}

		List<Node> nodes = new ArrayList<Node>();
		nodes.add(ul);
		return nodes;
	}

	private Node build(TreeNode<Permissions> node) {
		Permissions p = node.getData();

		Element container = new Element("li");
		container.setAttribute("id", p.getId().toString());
		container.addChild(new Text(p.getName()));
		
		Element ul = new Element("ul");
		for (TreeNode<Permissions> child : node.getChildren()) {
			ul.addChild(build(child));
		}

		container.addChild(ul);
		return container;
	}

}
